﻿using BaseTool;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security.Principal;

namespace StructuredLightSystemUI
{
    internal static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                bool test = false;
                if (test)
                {
                    WindowsIdentity identity = WindowsIdentity.GetCurrent();
                    WindowsPrincipal principal = new WindowsPrincipal(identity);
                    Application.EnableVisualStyles();
                    Application.Run(new MainForm());
                }
                else
                {
                    //判断客户端是否已打开
                    bool ret;
                    System.Threading.Mutex mutex = new System.Threading.Mutex(true, Application.ProductName, out ret);
                    if (!ret)
                    {
                        //已有打开的客户端，不能继续打开，程序退出
                        MessageBox.Show(null, "您已经打开了一个客户端，不能重复打开！", Application.ProductName);
                        Application.Exit();
                        return;
                    }

                    //判断当前登录用户是否为管理员
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    WindowsIdentity identity = WindowsIdentity.GetCurrent();
                    WindowsPrincipal principal = new WindowsPrincipal(identity);
                    if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
                    {
                        //如果是管理员，则直接运行
                        Application.Run(new MainForm());
                    }
                    else
                    {
                        //创建启动对象
                        ProcessStartInfo startInfo = new ProcessStartInfo();
                        startInfo.UseShellExecute = true;
                        startInfo.WorkingDirectory = Environment.CurrentDirectory;
                        startInfo.FileName = Application.ExecutablePath;
                        //设置启动动作,确保以管理员身份运行
                        startInfo.Verb = "runas";

                        Process.Start(startInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"打开程序异常，{ex.Message}", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
